<template>
  <el-card class="player-strength-analysis-card" shadow="never" v-if="playerStrengthAnalysisData">
    <template #header>
      <div class="card-header">
        <span class="card-title">球员组合演练场</span>
      </div>
    </template>
    
    <div class="player-strength-analysis-content">
      <!-- 均值和汇总统计信息表格 -->
      <div class="stats-container" v-if="playerStrengthAnalysisData">
        <el-card class="stats-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">球员实力均值统计</span>
            </div>
          </template>
          <el-table :data="meanStatsTableData" style="width: 100%;" size="small">
            <el-table-column prop="teamName" label="球队名称" width="90">
              <template #default="{ row }">
                <span class="team-name">{{ row.teamName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="goals" label="进球" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.goals }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="offensive" label="进攻" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.offensive }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="defensive" label="防守" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.defensive }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="overall" label="综合" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.overall }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="playerCount" label="总人数" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.playerCount }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card class="stats-card narrow-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">进攻分析 (仅进攻核心)</span>
            </div>
          </template>
          <el-table :data="offensiveAnalysisTableData" style="width: 100%;" size="small">
            <el-table-column prop="teamName" label="球队名称" width="85">
              <template #default="{ row }">
                <span class="team-name">{{ row.teamName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="offensiveMean" label="进攻均值" width="70">
              <template #default="{ row }">
                <span class="stat-value">{{ row.offensiveMean }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="offensiveMax" label="进攻最大值" width="80">
              <template #default="{ row }">
                <span class="stat-value">{{ row.offensiveMax }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="人数" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.count }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card class="stats-card narrow-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">防守分析 (仅防守基石)</span>
            </div>
          </template>
          <el-table :data="defensiveAnalysisTableData" style="width: 100%;" size="small">
            <el-table-column prop="teamName" label="球队名称" width="85">
              <template #default="{ row }">
                <span class="team-name">{{ row.teamName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="defensiveMean" label="防守均值" width="70">
              <template #default="{ row }">
                <span class="stat-value">{{ row.defensiveMean }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="defensiveMax" label="防守最大值" width="80">
              <template #default="{ row }">
                <span class="stat-value">{{ row.defensiveMax }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="人数" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.count }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-card class="stats-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">球员实力汇总统计</span>
            </div>
          </template>
          <el-table :data="sumStatsTableData" style="width: 100%;" size="small">
            <el-table-column prop="teamName" label="球队名称" width="90">
              <template #default="{ row }">
                <span class="team-name">{{ row.teamName }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="goals" label="进球" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.goals }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="offensive" label="进攻" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.offensive }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="defensive" label="防守" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.defensive }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="overall" label="综合" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.overall }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="playerCount" label="总人数" width="60">
              <template #default="{ row }">
                <span class="stat-value">{{ row.playerCount }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 主队球员实力分析 -->
      <div class="team-analysis home" v-if="playerStrengthAnalysisData.home">
        <div class="team-title">{{ playerStrengthAnalysisData.home[0]?.teamgbname || '主队' }} 球员实力分析</div>

        <el-table
          :data="playerStrengthAnalysisData.home"
          style="width: 100%"
          max-height="400"
          :default-sort="{ prop: 'overall_score_norm_index', order: 'descending' }"
        >
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="playername" label="球员姓名" width="120" fixed="left" />
          <el-table-column prop="player_category" label="位置" width="80" />
          <el-table-column prop="avg_goals" label="平均进球" :formatter="formatAvgGoals" />
          <el-table-column prop="offensive_score_norm_index" label="进攻能力" :formatter="formatScore" />
          <el-table-column prop="defensive_score_norm_index" label="防守能力" :formatter="formatScore" />
          <el-table-column prop="overall_score_norm_index" label="综合能力" :formatter="formatScore" sortable />
          <el-table-column prop="conversion_factor" label="折算系数" :formatter="formatConversionFactor" />
          <el-table-column prop="suspension_reason" label="停赛状态" :formatter="formatSuspension" />
          <el-table-column label="操作" width="80" fixed="right">
            <template #default="{ $index }">
              <el-button
                type="danger"
                size="small"
                @click="deleteRow('home', $index)"
                :icon="'Delete'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 客队球员实力分析 -->
      <div class="team-analysis away" v-if="playerStrengthAnalysisData.away">
        <div class="team-title">{{ playerStrengthAnalysisData.away[0]?.teamgbname || '客队' }} 球员实力分析</div>

        <el-table
          :data="playerStrengthAnalysisData.away"
          style="width: 100%"
          max-height="400"
          :default-sort="{ prop: 'overall_score_norm_index', order: 'descending' }"
        >
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column prop="playername" label="球员姓名" width="120" fixed="left" />
          <el-table-column prop="player_category" label="位置" width="80" />
          <el-table-column prop="avg_goals" label="平均进球" :formatter="formatAvgGoals" />
          <el-table-column prop="offensive_score_norm_index" label="进攻能力" :formatter="formatScore" />
          <el-table-column prop="defensive_score_norm_index" label="防守能力" :formatter="formatScore" />
          <el-table-column prop="overall_score_norm_index" label="综合能力" :formatter="formatScore" sortable />
          <el-table-column prop="conversion_factor" label="折算系数" :formatter="formatConversionFactor" />
          <el-table-column prop="suspension_reason" label="停赛状态" :formatter="formatSuspension" />
          <el-table-column label="操作" width="80" fixed="right">
            <template #default="{ $index }">
              <el-button
                type="danger"
                size="small"
                @click="deleteRow('away', $index)"
                :icon="'Delete'"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 没有数据显示提示 -->
      <div class="no-data" v-if="!playerStrengthAnalysisData.home && !playerStrengthAnalysisData.away">
        <el-empty description="暂无球员实力分析数据" />
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { PlayerStrengthAnalysisData } from '../apis/type'

// 定义组件属性
interface Props {
  playerStrengthAnalysisData: {
    home: PlayerStrengthAnalysisData[] | null
    away: PlayerStrengthAnalysisData[] | null
  } | null
}

const props = defineProps<Props>()

// 计算统计数据
const calculateStats = (data: PlayerStrengthAnalysisData[] | null) => {
  if (!data || data.length === 0) {
    return {
      avgGoals: 0,
      avgOffensive: 0,
      avgDefensive: 0,
      avgOverall: 0,
      avgConversion: 0,
      sumGoals: 0,
      sumOffensive: 0,
      sumDefensive: 0,
      sumOverall: 0,
      sumConversion: 0,
    }
  }

  let count = 0;
  let sumGoals = 0;
  let sumOffensive = 0;
  let sumDefensive = 0;
  let sumOverall = 0;
  let sumConversion = 0;

  for (const player of data) {
    if (player.avg_goals !== null && player.avg_goals !== undefined) {
      sumGoals += player.avg_goals;
      count++;
    }
    if (player.offensive_score_norm_index !== null && player.offensive_score_norm_index !== undefined) {
      sumOffensive += player.offensive_score_norm_index;
    }
    if (player.defensive_score_norm_index !== null && player.defensive_score_norm_index !== undefined) {
      sumDefensive += player.defensive_score_norm_index;
    }
    if (player.overall_score_norm_index !== null && player.overall_score_norm_index !== undefined) {
      sumOverall += player.overall_score_norm_index;
    }
    if (player.conversion_factor !== null && player.conversion_factor !== undefined) {
      sumConversion += player.conversion_factor;
    }
  }

  return {
    avgGoals: count > 0 ? sumGoals / count : 0,
    avgOffensive: data.length > 0 ? sumOffensive / data.length : 0,
    avgDefensive: data.length > 0 ? sumDefensive / data.length : 0,
    avgOverall: data.length > 0 ? sumOverall / data.length : 0,
    avgConversion: data.length > 0 ? sumConversion / data.length : 0,
    sumGoals,
    sumOffensive,
    sumDefensive,
    sumOverall,
    sumConversion,
  }
}

// 计算主队统计数据
const homeStats = computed(() => {
  return calculateStats(props.playerStrengthAnalysisData?.home || null)
})

// 计算客队统计数据
const awayStats = computed(() => {
  return calculateStats(props.playerStrengthAnalysisData?.away || null)
})

// 计算主队统计表格数据
const homeStatsTableData = computed(() => {
  if (!props.playerStrengthAnalysisData?.home) {
    return []
  }
  const data = props.playerStrengthAnalysisData.home
  const stats = calculateStats(data)
  const teamName = data[0]?.teamgbname || '主队'
  const playerCount = data.length

  return [
    {
      type: '均值',
      teamName: teamName,
      goals: stats.avgGoals.toFixed(2),
      offensive: stats.avgOffensive.toFixed(3),
      defensive: stats.avgDefensive.toFixed(3),
      overall: stats.avgOverall.toFixed(3),
      playerCount: playerCount
    },
    {
      type: '汇总',
      teamName: teamName,
      goals: stats.sumGoals.toFixed(2),
      offensive: stats.sumOffensive.toFixed(3),
      defensive: stats.sumDefensive.toFixed(3),
      overall: stats.sumOverall.toFixed(3),
      playerCount: playerCount
    }
  ]
})

// 计算客队统计表格数据
const awayStatsTableData = computed(() => {
  if (!props.playerStrengthAnalysisData?.away) {
    return []
  }
  const data = props.playerStrengthAnalysisData.away
  const stats = calculateStats(data)
  const teamName = data[0]?.teamgbname || '客队'
  const playerCount = data.length

  return [
    {
      type: '均值',
      teamName: teamName,
      goals: stats.avgGoals.toFixed(2),
      offensive: stats.avgOffensive.toFixed(3),
      defensive: stats.avgDefensive.toFixed(3),
      overall: stats.avgOverall.toFixed(3),
      playerCount: playerCount
    },
    {
      type: '汇总',
      teamName: teamName,
      goals: stats.sumGoals.toFixed(2),
      offensive: stats.sumOffensive.toFixed(3),
      defensive: stats.sumDefensive.toFixed(3),
      overall: stats.sumOverall.toFixed(3),
      playerCount: playerCount
    }
  ]
})

// 计算均值统计表格数据（包含主队和客队）
const meanStatsTableData = computed(() => {
  const result = []

  // 添加主队均值数据
  if (props.playerStrengthAnalysisData?.home) {
    const homeData = props.playerStrengthAnalysisData.home
    const homeStats = calculateStats(homeData)
    const teamName = homeData[0]?.teamgbname || '主队'
    const playerCount = homeData.length

    result.push({
      teamName: teamName,
      goals: homeStats.avgGoals.toFixed(2),
      offensive: homeStats.avgOffensive.toFixed(2),
      defensive: homeStats.avgDefensive.toFixed(2),
      overall: homeStats.avgOverall.toFixed(2),
      playerCount: playerCount
    })
  }

  // 添加客队均值数据
  if (props.playerStrengthAnalysisData?.away) {
    const awayData = props.playerStrengthAnalysisData.away
    const awayStats = calculateStats(awayData)
    const teamName = awayData[0]?.teamgbname || '客队'
    const playerCount = awayData.length

    result.push({
      teamName: teamName,
      goals: awayStats.avgGoals.toFixed(2),
      offensive: awayStats.avgOffensive.toFixed(2),
      defensive: awayStats.avgDefensive.toFixed(2),
      overall: awayStats.avgOverall.toFixed(2),
      playerCount: playerCount
    })
  }

  return result
})

// 计算汇总统计表格数据（包含主队和客队）
const sumStatsTableData = computed(() => {
  const result = []

  // 添加主队汇总数据
  if (props.playerStrengthAnalysisData?.home) {
    const homeData = props.playerStrengthAnalysisData.home
    const homeStats = calculateStats(homeData)
    const teamName = homeData[0]?.teamgbname || '主队'
    const playerCount = homeData.length

    result.push({
      teamName: teamName,
      goals: homeStats.sumGoals.toFixed(2),
      offensive: homeStats.sumOffensive.toFixed(2),
      defensive: homeStats.sumDefensive.toFixed(2),
      overall: homeStats.sumOverall.toFixed(2),
      playerCount: playerCount
    })
  }

  // 添加客队汇总数据
  if (props.playerStrengthAnalysisData?.away) {
    const awayData = props.playerStrengthAnalysisData.away
    const awayStats = calculateStats(awayData)
    const teamName = awayData[0]?.teamgbname || '客队'
    const playerCount = awayData.length

    result.push({
      teamName: teamName,
      goals: awayStats.sumGoals.toFixed(2),
      offensive: awayStats.sumOffensive.toFixed(2),
      defensive: awayStats.sumDefensive.toFixed(2),
      overall: awayStats.sumOverall.toFixed(2),
      playerCount: playerCount
    })
  }

  return result
})

// 计算进攻核心球员统计数据
const calculateOffensiveStats = (data: PlayerStrengthAnalysisData[] | null) => {
  if (!data || data.length === 0) {
    return {
      avgOffensive: 0,
      maxOffensive: 0,
      count: 0
    }
  }

  // 过滤出停赛状态正常的球员
  const normalSuspendedPlayers = data.filter(player => {
    return !player.suspension_reason || player.suspension_reason === '正常' || player.suspension_reason === '';
  });

  // 按进攻能力降序排列
  const sortedPlayers = normalSuspendedPlayers.sort((a, b) => {
    if (b.offensive_score_norm_index != null && a.offensive_score_norm_index != null) {
      return b.offensive_score_norm_index - a.offensive_score_norm_index;
    }
    return 0;
  });

  // 选择前4名球员
  const top4Players = sortedPlayers.slice(0, 4);

  if (top4Players.length === 0) {
    return {
      avgOffensive: 0,
      maxOffensive: 0,
      count: 0
    }
  }

  let sumOffensive = 0
  let maxOffensive = 0

  for (const player of top4Players) {
    if (player.offensive_score_norm_index != null) {
      sumOffensive += player.offensive_score_norm_index
      if (player.offensive_score_norm_index > maxOffensive) {
        maxOffensive = player.offensive_score_norm_index
      }
    }
  }

  return {
    avgOffensive: top4Players.length > 0 ? sumOffensive / top4Players.length : 0,
    maxOffensive: maxOffensive,
    count: top4Players.length
  }
}

// 计算防守基石球员统计数据
const calculateDefensiveStats = (data: PlayerStrengthAnalysisData[] | null) => {
  if (!data || data.length === 0) {
    return {
      avgDefensive: 0,
      maxDefensive: 0,
      count: 0
    }
  }

  // 过滤出停赛状态正常的球员
  const normalSuspendedPlayers = data.filter(player => {
    return !player.suspension_reason || player.suspension_reason === '正常' || player.suspension_reason === '';
  });

  // 按防守能力降序排列
  const sortedPlayers = normalSuspendedPlayers.sort((a, b) => {
    if (b.defensive_score_norm_index != null && a.defensive_score_norm_index != null) {
      return b.defensive_score_norm_index - a.defensive_score_norm_index;
    }
    return 0;
  });

  // 选择前4名球员
  const top4Players = sortedPlayers.slice(0, 4);

  if (top4Players.length === 0) {
    return {
      avgDefensive: 0,
      maxDefensive: 0,
      count: 0
    }
  }

  let sumDefensive = 0
  let maxDefensive = 0

  for (const player of top4Players) {
    if (player.defensive_score_norm_index != null) {
      sumDefensive += player.defensive_score_norm_index
      if (player.defensive_score_norm_index > maxDefensive) {
        maxDefensive = player.defensive_score_norm_index
      }
    }
  }

  return {
    avgDefensive: top4Players.length > 0 ? sumDefensive / top4Players.length : 0,
    maxDefensive: maxDefensive,
    count: top4Players.length
  }
}

// 计算进攻分析表格数据（包含主队和客队的进攻核心球员数据）
const offensiveAnalysisTableData = computed(() => {
  const result = []

  // 添加主队进攻核心数据
  if (props.playerStrengthAnalysisData?.home) {
    const homeData = props.playerStrengthAnalysisData.home
    const homeStats = calculateOffensiveStats(homeData)
    const teamName = homeData[0]?.teamgbname || '主队'

    result.push({
      teamName: teamName,
      offensiveMean: homeStats.avgOffensive.toFixed(2),
      offensiveMax: homeStats.maxOffensive.toFixed(2),
      count: homeStats.count
    })
  }

  // 添加客队进攻核心数据
  if (props.playerStrengthAnalysisData?.away) {
    const awayData = props.playerStrengthAnalysisData.away
    const awayStats = calculateOffensiveStats(awayData)
    const teamName = awayData[0]?.teamgbname || '客队'

    result.push({
      teamName: teamName,
      offensiveMean: awayStats.avgOffensive.toFixed(2),
      offensiveMax: awayStats.maxOffensive.toFixed(2),
      count: awayStats.count
    })
  }

  return result
})

// 计算防守分析表格数据（包含主队和客队的防守基石球员数据）
const defensiveAnalysisTableData = computed(() => {
  const result = []

  // 添加主队防守基石数据
  if (props.playerStrengthAnalysisData?.home) {
    const homeData = props.playerStrengthAnalysisData.home
    const homeStats = calculateDefensiveStats(homeData)
    const teamName = homeData[0]?.teamgbname || '主队'

    result.push({
      teamName: teamName,
      defensiveMean: homeStats.avgDefensive.toFixed(2),
      defensiveMax: homeStats.maxDefensive.toFixed(2),
      count: homeStats.count
    })
  }

  // 添加客队防守基石数据
  if (props.playerStrengthAnalysisData?.away) {
    const awayData = props.playerStrengthAnalysisData.away
    const awayStats = calculateDefensiveStats(awayData)
    const teamName = awayData[0]?.teamgbname || '客队'

    result.push({
      teamName: teamName,
      defensiveMean: awayStats.avgDefensive.toFixed(2),
      defensiveMax: awayStats.maxDefensive.toFixed(2),
      count: awayStats.count
    })
  }

  return result
})

// 定义emit
const emit = defineEmits(['data-updated'])

// 删除行函数
const deleteRow = (team: 'home' | 'away', index: number) => {
  if (team === 'home' && props.playerStrengthAnalysisData?.home) {
    const newData = [...props.playerStrengthAnalysisData.home]
    newData.splice(index, 1)
    emit('data-updated', { home: newData, away: props.playerStrengthAnalysisData.away })
  } else if (team === 'away' && props.playerStrengthAnalysisData?.away) {
    const newData = [...props.playerStrengthAnalysisData.away]
    newData.splice(index, 1)
    emit('data-updated', { home: props.playerStrengthAnalysisData.home, away: newData })
  }
}

// 格式化数值显示
const formatScore = (row: any, column: any, cellValue: number | null) => {
  if (cellValue === null || cellValue === undefined) {
    return '-'
  }
  return cellValue.toFixed(3)
}

const formatAvgGoals = (row: any, column: any, cellValue: number | null) => {
  if (cellValue === null || cellValue === undefined) {
    return '-'
  }
  return cellValue.toFixed(2)
}

const formatConversionFactor = (row: any, column: any, cellValue: number | null) => {
  if (cellValue === null || cellValue === undefined) {
    return '-'
  }
  return cellValue.toFixed(2)
}

const formatSuspension = (row: any, column: any, cellValue: string | null) => {
  if (!cellValue) {
    return '正常'
  }
  return cellValue
}

// 监听数据变化
watch(() => props.playerStrengthAnalysisData, (newVal) => {
  if (newVal) {
    // console.log('Player strength analysis data updated:', newVal)
  }
}, { deep: true })
</script>

<style scoped>
.player-strength-analysis-card {
  margin-top: 5px;
  width: 100%;
  box-sizing: border-box;
}

.player-strength-analysis-content {
  padding: 10px 0;
  width: 100%;
}

.team-analysis {
  padding: 10px;
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
}

.team-title {
  text-align: center;
  margin: 10px 0;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}

/* 统计信息容器样式 */
.stats-container {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stats-card {
  flex: 1;
  margin-bottom: 0;
}

.narrow-card {
  flex: 0.7; /* Make these cards narrower than others */
}

/* 确保内容区域占满宽度 */
.player-strength-analysis-content {
  padding: 10px 0;
  width: 100%;
  box-sizing: border-box;
}

.stats-card .el-card__header {
  padding: 10px 15px;
  background-color: #f8f9fa;
}

.card-title {
  font-weight: bold;
  color: #303133;
}

/* 统计信息表格样式 */
.team-name {
  font-weight: bold;
  color: #606266;
}

.stat-value {
  font-weight: bold;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-container {
    flex-direction: column;
  }
}

/* 表格样式 */
:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table .el-table__row) {
  height: 40px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

/* 确保卡片体内容区域占满宽度 */
:deep(.el-card__body) {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

/* 确保表格容器占满卡片宽度 */
.team-analysis {
  padding: 10px;
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .team-analysis {
    width: 100%;
    box-sizing: border-box;
  }

  .stats-container {
    flex-direction: column;
  }
}
</style>
